package de.hdu.pms.ho.dao;

import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.sun.xml.internal.bind.v2.model.core.ID;

import de.hdu.pms.ho.model.Kunde;

/**
 * The class {@link KundeDao} is the class which saves all necessary  
   functions for all applications with {@link Kunde} content.
 * 
 * @author Hendrik Neumann
 */
public class KundeDao extends HibernateDaoSupport {
	
	public static Logger log = Logger.getLogger(KundeDao.class);
	
	
	/**
	 * Creates a new {@link Kunde} and saves it in the database.
	 * @param vorname
	 * @param name
	 * @param kontonummer
	 */
	public int create(String v, String n, Integer k) {
		Kunde k2 = new Kunde(v,n,k);
		save(k2);
		return k2.getId();
	}
	
	/*public void create(String vorname, String name, String telefonnummer) {
		HibernateTemplate template = getHibernateTemplate();
		Kunde kunde = new Kunde(vorname, name, telefonnummer);
		template.persist(kunde);
	}*/
	
	/**
	 * @param id gives back the {@link ID}, the primary key from the 
	   {@link Kunde} in the database, and allows you finding the right one.
	 * @return the {@link ID}, the primary key from {@link Kunde}.
	 */
	public Kunde findById(int id) {
		HibernateTemplate template = getHibernateTemplate();
		return (Kunde) template.get(Kunde.class, id);
	}
	
	/**
	 * Saves the {@link Kunde} specified by the parameters in the database.
	 * @param kunde {@link Kunde} object that will be saved in the database.
	 * @return the object specified by the parameters.
	 */
	public Kunde save(Kunde kunde) {
		HibernateTemplate template = getHibernateTemplate();
		template.saveOrUpdate(kunde);
		log.debug("Kunde id=" + kunde.getId());
		return kunde;
	}

	/**
	 * Deletes the {@link Kunde} from the database.
	 * @param kunde selected {@link Kunde} will deleted from the database. 
	 */
	public void delete(Kunde kunde) {
		HibernateTemplate template = getHibernateTemplate();
		template.delete(kunde);
	}
	
	/**
	 * Deletes a specified object in the database
	 * @param id primary key of the object that should be deleted,
	 * because of the NestedServletException
	 */
	public void deletebyId(Integer id){	
		HibernateTemplate template = getHibernateTemplate();
		Kunde k = findById(id);
		template.delete(k);
		template.flush();
	}
	
	/**
	 * Will show you all {@link Kunde} that are saved in the database.
	 * @return all {@link Kunde} in a list.
	 */
	public List<Kunde> findAll() {
		HibernateTemplate template = getHibernateTemplate();
		return template.loadAll(Kunde.class);
	}
		
}
